package com.cqupt.sendMes.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.cqupt.sendMes.enums.HttpStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : zhanghao
 * @create 2024/10/9 14:18
 */

@Component
@Slf4j
public class WxPush {


    @Autowired
    HttpUtils httpUtils;


    public Result returnRes(String originStr){
        return JSONObject.parseObject(originStr, Result.class);
    }

    /**
     * 发送消息
     */
    public Result send(Message message) {
        if(Boolean.FALSE.equals(verify(message))){
            return null;
        }
        String res = httpUtils.post("/api/send/message",message);
        if(ObjectUtil.isEmpty(res)){
            log.warn("发送消息失败！，请检查http调用");
            return null;
        }
//        Result sendResult = JSONObject.parseObject(res, Result.class);
//        if (sendResult.isSuccess()) {
//            //转换，方便调用
//            Object data = sendResult.getData();
//            String s = JSONObject.toJSONString(data);
//            List<MessageRes> messageResults = JSONObject.parseObject(s, new TypeReference<List<MessageRes>>() {});
//
//            sendResult.setData(messageResults);
//        }
//        return sendResult;
        return returnRes(res);
    }

    /**
     * 查询消息发送状态
     */
    public Result queryMessageStatus(Long messageId){
        if (ObjectUtil.isEmpty(messageId)){
            log.warn("messageId为空，请检查");
            return new Result(HttpStatusEnum.WXP_BIZ_FAIL.getCode(), "messageId为空");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("sendRecordId", messageId.toString());
        String res = httpUtils.get("/api/send/query/status", params);
        return returnRes(res);
    }


    /**
     * 验证消息合法性，客户端验证比较宽松，主要在服务端进行校验
     */
    private Boolean verify(Message message) {
        if (ObjectUtil.isEmpty(message)) {
            log.warn("消息体不可为空");
            return false;
        }
        if (ObjectUtil.isEmpty(message.getAppToken())) {
            log.warn("appToken不可为空");
            return false;
        }
        return true;
    }

}
